class Token {
    // 注册几个Token类型
    static PLUS = 1;
    static INT = 2;

    type : number;
    text:string 

    constructor(type:number,text:string = ""){
        this.type = type;
        this.text = text;
    }

    toString(){
        return this.text
    }
}
/**
 * 同型AST节点
 * 语法树全部使用AST作为节点描述
 */
class AST {
    token:Token | null;
    children:AST[] = [];

    constructor(token:Token | null = null){
        this.token = token;
    }

    getNodeType(){
        return this.token?.type;
    }

    addChild(t:AST){
        this.children.push(t)
    }

    isNil(){
        return this.token == null;
    }

    toString(){
        return this.isNil() ? 'nil' : this.token?.toString();
    }

    /**
     * 打印语法树
     */
    toStringTree(){
        if(this.children.length > 0){
            let buf = "";
            // 根节点输出
            if(!this.isNil()){
                buf += "(";
                buf += this.toString();
                buf += "  ";
            }
            //子节点输出
            this.children.forEach((t,i)=> {
                if(i > 0 ){
                    buf += " "
                }
                buf += t.toStringTree()
            })

            if(!this.isNil()){
                buf += ")";
            }
            return buf;
        }else{
            return this.toString()
        }
    }
}

export {
    Token,
    AST
}